import {messages} from "share/common";
import React from 'react'
import ReactDOM from 'react-dom';
import {Modal, Icon, Badge, message} from 'antd/lib/index'
import 'styles/components/image-viewer.scss'
import wordImage from "images/file-type/word.png";
import pptImage from "images/file-type/ppt.png";
import excelImage from "images/file-type/excel.png";
import txtImage from "images/file-type/txt.png";
import pdfImage from "images/file-type/pdf.png";
import unknownImage from "images/file-type/unknown.png";

/**
 * 图片查看组件，支持放大、缩小、旋转操作
 *
 * 2018/11/26 ZaraNengap
 * 非常简陋，但是当时没有UI、UX
 * 所以够用就行，不想花时间在优化这玩意上面
 * 毕竟产品经理觉得很好 :)
 */
class FileViewer extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      nowIndex: 0,
      isFixedLocation: true, //是否允许自动滚动条定位，将nowIndex图片居中
    };
    this.moving = false;  //图片移动状态
    this.startXY = {};  //图片移动前时记录xy值
    this.webId = {
      'cloudhelios-1255326279.cos.ap-shanghai.myqcloud.com': '19380',
      'cloudhelios.oss-cn-shanghai.aliyuncs.com': '19381',
      'helioscloud-uat.oss-cn-shanghai.aliyuncs.com': '19390',
      'huilianyi-oss.huilianyi.com': '19384',
      'helioscloud-uat-static.oss-cn-shanghai.aliyuncs.com': '19385',
      'cos-cloudhelios-tc-sh.huilianyi.com': '19386',
      'cos-cloudhelios-static-tc-sh.huilianyi.com': '19387',
      'cloudhelios-static.oss-cn-shanghai.aliyuncs.com': '19388',
      'su.bcebos.com': '19524',
      'cloudhelios.su.bcebos.com': '19525'
    }
  }

  componentWillMount() {
    this.setState({nowIndex: this.props.defaultIndex});
  }

  componentWillReceiveProps(nextProps) {
    this.setState({nowIndex: nextProps.defaultIndex});
    if (nextProps.visible) {
      this.setState({isFixedLocation: true});
    }
  }

  onMouseMove = (e) => {
    e.stopPropagation();
    if(this.moving){
      let imageDom = ReactDOM.findDOMNode(this.refs.imageRef);
      //与记录值的偏移量
      let offsetX = e.clientX - this.startXY.X;
      let offsetY = e.clientY - this.startXY.Y;
      let originLeft = 0;
      let originTop = 0;
      let imageLeft = imageDom.style.left;
      let imageTop = imageDom.style.top;
      //取得原本left、top值
      if(imageLeft){
        originLeft = Number(imageLeft.substr(0, imageLeft.indexOf('px')));
      }
      if(imageTop){
        originTop = Number(imageTop.substr(0, imageTop.indexOf('px')));
      }
      imageDom.style.left = (originLeft + offsetX) + 'px';
      imageDom.style.top = (originTop + offsetY) + 'px';
      //设置后重制记录值
      this.startXY = {X: e.clientX, Y: e.clientY};
    }
  };

  onMouseUp = (e) => {
    e.stopPropagation();
    this.moving = false;
  };

  onMouseDown = (e) => {
    e.stopPropagation();
    this.startXY = {X: e.clientX, Y: e.clientY};
    this.moving = true;
  };

  componentDidUpdate() {
    const { nowIndex, isFixedLocation } = this.state;
    const { attachments } = this.props;
    //锁定缩略图移动到对应位置
    let thumbDom = ReactDOM.findDOMNode(this.refs.thumbRef);
    if (isFixedLocation && thumbDom && attachments.length > 9) {
      if (nowIndex <= 4) {
        setTimeout(() => {
          if (thumbDom.scrollTo) {
            thumbDom.scrollTo({
              left: 0,
              behavior: "smooth"
            });
          } else {
            thumbDom.scrollLeft = 0;
          }
        }, 500);
      } else {
        setTimeout(() => {
          if (thumbDom.scrollTo) {
            thumbDom.scrollTo({
              left: 70 * (nowIndex - 4),
              behavior: "smooth"
            });
          } else {
            thumbDom.scrollLeft = 70 * (nowIndex - 4);
          }
        }, 500);
      }
      this.setState({isFixedLocation: false});
    }
  }

  initialImageStyle = () => {
    let imageDom = ReactDOM.findDOMNode(this.refs.imageRef);
    if( imageDom ) {
      imageDom.style.transform = '';
      imageDom.style.top = '0px';
      imageDom.style.left = '0px';
    }
  };

  handleSelectAttachment = (index) => {
    const { onClick } = this.props;
    this.setState({ nowIndex: index }, () => {
      this.initialImageStyle();
      onClick && onClick(index);
    });
  };

  handleOperateImage = (operate) => {
    let imageDom = ReactDOM.findDOMNode(this.refs.imageRef);
    let transformStyle = imageDom.style.transform;
    let rotateZ = 0, scale = 1;
    //得到rotateZ值
    transformStyle.replace(/rotateZ\(((\d+)|(-\d+))deg\)/, (target,$1) => {rotateZ = Number($1); return target});
    //得到scale值
    transformStyle.replace(/scale\(((\d+.\d+)|(\d+))\)/, (target,$1) => {scale = Number($1); return target});
    switch(operate){
      //放大，最大2
      case 'plus': {
        if(scale < 2)
          scale += 0.2;
        break;
      }
      //缩小，最小1
      case 'minus': {
        if(scale > 1)
          scale -= 0.2;
        break;
      }
      //向左旋转
      case 'left': {
        rotateZ -= 90;
        break;
      }
      //向又旋转
      case 'right': {
        rotateZ += 90;
        break;
      }
    }
    imageDom.style.transform = `rotateZ(${rotateZ}deg) scale(${scale})`
  };

  //操作thumb list的左右箭头 left左移一位，right右移一位
  handleOperateThumb = (type) => {
    const { nowIndex } = this.state;
    const { attachments } = this.props;
    let thumbDom = ReactDOM.findDOMNode(this.refs.thumbRef);
    if (thumbDom) {
      if (thumbDom.scrollTo) {
        thumbDom.scrollTo({
          left: type === 'left' ? thumbDom.scrollLeft - 70 : thumbDom.scrollLeft + 70,
          behavior: "smooth"
        });
      } else {
        thumbDom.scrollLeft = type === 'left' ? thumbDom.scrollLeft - 70 : thumbDom.scrollLeft + 70;
      }
      //不是第一张 且 不是最后一张的时候
      //第一张可右移，最后一张可左移
      if (attachments.length > 1 && ((nowIndex !== 0 && nowIndex !== attachments.length - 1)
        || (nowIndex === 0 && type === 'right')
        || (nowIndex === attachments.length - 1 && type === 'left'))
      ) {
        this.setState({ nowIndex: type === 'left' ? nowIndex - 1 : nowIndex + 1 }, this.initialImageStyle);
      }
    }
  };

  handleDownloadFile = file => {
    const { urlKey } = this.props;
    window.open(file[urlKey], '_blank');
  };

  //缩略图，封面图
  getImage = (file) => {
    let extension = this.getExtension(file);
    console.log('extension', extension, file)
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    let wordExtension = ['doc', 'docx'];
    let pptExtension = ['ppt', 'pptx'];
    let excelExtension = ['xls', 'xlsx'];
    let txtExtension = ['txt'];
    let pdfExtension = ['pdf', 'ofd'];
    if(imageExtension.has(extension))
      return file.thumbnailUrl || file.fileURL || file.url;
    if(wordExtension.has(extension))
      return wordImage;
    if(pptExtension.has(extension))
      return pptImage;
    if(excelExtension.has(extension))
      return excelImage;
    if(txtExtension.has(extension))
      return txtImage;
    if(pdfExtension.has(extension))
      return pdfImage;
    return unknownImage;
  };

  //附件是否为图片
  isImage = (file) => {
    let imageExtension = ['png', 'gif', 'jpg', 'jpeg', 'bmp'];
    return imageExtension.has(this.getExtension(file));
  };

  isPDF = (file) => {
    let pdfExtension = ['pdf', 'ofd'];
    return pdfExtension.has(this.getExtension(file));
  };

  //附件格式是否合法
  isAllowedFile = file => {
    let allowedSuffix = ['txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'wps'];
    return allowedSuffix.has(this.getExtension(file));
  };

  getExtension = file => {
    let fileName = file.fileName || file.name || (file.response ? (file.response.fileName || file.response.name || '') : '');
    let sections = fileName.split('.');
    return sections[sections.length - 1].toLowerCase();
  };

  // getUrl = (url, host) => `https://ow365.cn/?i=${this.webId[host]}&furl=${encodeURIComponent(url)}&ssl=1`;
  // getUrl = (url, host) => `https://office365.huilianyi.com/?furl=${encodeURIComponent(url)}&ssl=1`;
  // getUrl = (url, host) => `https://office365.huilianyi.com/?furl=${url}`;
  getUrl = (url, host) => {
    console.log("url", url)
    if (url.indexOf('tes-static') !== -1) {
      return `https://office365.huilianyi.com/?ssl=1&furl=${url}`;
    }
    return `https://office365.huilianyi.com/?furl=${encodeURIComponent(url)}&ssl=1`;
  }

  renderAttachment = file => {
    const { urlKey, result } = this.props;
    let url = file ? file[urlKey] : '';
    console.log("url", file)
    if (result && result[0]) {
      url = result[0].fileURL;
    }
    try {
      if(!file)
        return ;
      if(!url)
        return <div className='font-ghost'>{messages('components.key978')/*该附件不存在或已失效*/}</div>;
      if(this.isImage(file))
        return (
          <img
            src={url}
            ref="imageRef"
            draggable={false}
            onMouseDown={this.onMouseDown}
            onMouseMove={this.onMouseMove}
            onMouseUp={this.onMouseUp}
          />);
      if (this.isPDF(file)) {
        return <iframe src={url}/>;
      }
      if(this.isAllowedFile(file)) {
        url = `https://${url.split("://")[1]}`;
        let host = url.split("://")[1].split('/')[0];
        return <iframe src={this.getUrl(url, host)}/>;
      }
      return <div className='font-ghost'>{messages('components.key979')/*暂不支持此格式*/}</div>
    } catch(e) {
      return <div className='font-ghost'>{messages('components.key979')/*暂不支持此格式*/}</div>
    }
  };

  render() {
    const { nowIndex } = this.state;
    const { visible, afterClose, onCancel, attachments, valueKey, modalParams, markable, markKey } = this.props;
    return (
      <Modal
        className="image-view"
        visible={visible}
        afterClose={afterClose}
        footer={null}
        onCancel={onCancel}
        width={1092}
        {...modalParams}
      >
        {attachments[nowIndex] && (
          <div>
            <div className={"attachment-title-area"}>{attachments[nowIndex]["name"]}</div>
            <div className="attachment-area">
              {this.renderAttachment(attachments[nowIndex])}
            </div>
            <div className="attachment-operate">
              {nowIndex + 1}/{attachments.length}
              <div className="attachment-operate-icon">
                {this.isImage(attachments[nowIndex]) &&
                  <span>
                    <Icon type="plus" onClick={() => this.handleOperateImage('plus')}/>
                    <Icon type="minus" onClick={() => this.handleOperateImage('minus')}/>
                    <Icon type="swap-left" onClick={() => this.handleOperateImage('left')}/>
                    <Icon type="swap-right" onClick={() => this.handleOperateImage('right')}/>
                  </span>
                }
                <span>
                  {!this.isImage(attachments[nowIndex]) && <span>{messages('components.key1003')/*如预览失败请点击下载文件查看*/}</span>}
                  <Icon type="download" onClick={() => this.handleDownloadFile(attachments[nowIndex])}/>
                </span>
              </div>
            </div>
            <div className="attachment-list">
              <Icon
                type="left"
                className="attachment-list-icon attachment-list-left-icon"
                onClick={() => this.handleOperateThumb('left')}
              />
              <Icon
                type="right"
                className="attachment-list-icon attachment-list-right-icon"
                onClick={() => this.handleOperateThumb('right')}
              />
              <div className="attachment-list-box" ref="thumbRef">
                {attachments.map((file, index) => {
                  return markable ? (
                    <Badge
                      status={file[markKey] ? 'success' : 'error'}
                      key={file.id}
                      offset={[0, -10]}
                    >
                      <img
                        src={this.getImage(file)}
                        key={file[valueKey]}
                        className={`${index === nowIndex && 'selected-attachment'}`}
                        onClick={() => this.handleSelectAttachment(index)}
                      />
                    </Badge>
                  ) : (
                    <img
                      src={this.getImage(file)}
                      key={file[valueKey]}
                      className={`${index === nowIndex && 'selected-attachment'}`}
                      onClick={() => this.handleSelectAttachment(index)}
                    />
                  )
                })}
              </div>
            </div>
          </div>
        )}
      </Modal>
    )
  }
}

FileViewer.propTypes = {
  visible: React.PropTypes.bool.isRequired,
  attachments: React.PropTypes.array.isRequired,
  afterClose: React.PropTypes.func,
  onCancel: React.PropTypes.func,
  urlKey: React.PropTypes.string,  //url字段
  thumbnailUrlKey: React.PropTypes.string,//缩略图URL字段
  valueKey: React.PropTypes.string,  //key值字段
  defaultIndex: React.PropTypes.number,  //默认预览图片的index
  modalParams: React.PropTypes.object, //额外的模态框参数
  markable: React.PropTypes.bool, //是否在缩略图上做标记
  markKey: React.PropTypes.string, //标记值字段
  onClick: React.PropTypes.func //点击文件缩略图列表回调,返回文件index
};

FileViewer.defaultProps = {
  visible: false,
  attachments: [],
  urlKey: 'url',
  thumbnailUrlKey: 'thumbnailUrl',
  valueKey: 'uid',
  defaultIndex: 0,
  modalParams: {},
  markable: false
};

export default FileViewer
